//
//  RPWebViewController.m
//  Rippton2.0
//
//  Created by hxh on 2020/4/22.
//  Copyright © 2020 胡旭辉. All rights reserved.
//

#import "CommonWebViewController.h"
#import "HomePageDetailViewController.h"
#import "HomePageItemModel.h"
#import "HomePageWebShareModel.h"
#import "RPAppShareView.h"
#import "WebUserInfoModel.h"
#import "WebDeviceModel.h"
#import "WebShareModel.h"
#import "WebActionModel.h"
#import "WebSystemModel.h"
#import "LoginViewController.h"
@interface CommonWebViewController ()<WKNavigationDelegate,WKScriptMessageHandler>

@property (nonatomic,assign)BOOL isLoadFinish;
@property (nonatomic,strong)HomePageWebShareModel *shareItem;
@end

@implementation CommonWebViewController


- (UIStatusBarStyle)preferredStatusBarStyle {
    if (self.isDark) {
        return UIStatusBarStyleLightContent;
    }
    return UIStatusBarStyleDefault;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    [self addAllScriptMsgHandle];
    
    if (self.isDark) {
        self.navigationController.navigationBar.barTintColor = C21;
        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
        self.navigationController.navigationBar.translucent = NO;
        [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    }
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = YES;
    
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    if (self.isDark) {
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
        self.navigationController.navigationBar.tintColor = [UIColor colorWithHexString:@"#666666"];
        self.navigationController.navigationBar.translucent = YES;
        [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
    }
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = NO;
    
    [self removeAllScriptMsgHandle];
}




- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([RPAppManager isShowNetworkView]) {
        @zf_weakify(self)
        [self showNetworkErrorWithNavTitle:@"" completeBlock:^{
           @zf_strongify(self)
            [self setUI];
        } cancelBlock:^{
            @zf_strongify(self)
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }else{
        [self setUI];
    }
    
    self.view.backgroundColor = self.isDark?C21:[UIColor whiteColor];
    self.webView.backgroundColor = self.isDark?C21:[UIColor whiteColor];
    self.isHideNavBar = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateWebLoginStatus) name:@"updateUserInfoSource" object:nil];
}
- (void)back{
    if ([self.webView canGoBack]) {
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]init];
        self.navigationItem.rightBarButtonItem = rightItem;
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)updateWebLoginStatus{
    
    [self.webView evaluateJavaScript:[NSString stringWithFormat:@"loginSuccess('%@')",[RPAppManager getCustomerId]] completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
    }];
    
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"eventType"] = @"user";
    param[@"action"] = @"login";
    param[@"userId"] = [RPAppManager getCustomerId];

    [self.webView evaluateJavaScript:[NSString stringWithFormat:@"ddupOnEvent(%@)",[param mj_JSONString]] completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
    }];
}

- (void)setUI{
    
    WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore];
    [dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes] completionHandler:^(NSArray<WKWebsiteDataRecord *> * _Nonnull records) {
        for (WKWebsiteDataRecord *record in records){
            [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes forDataRecords:@[record] completionHandler:^{

            }];
        }
    }];

//    NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width,user-scalable=no'); document.getElementsByTagName('head')[0].appendChild(meta);";
//    WKUserScript *wkUScript =[[WKUserScript alloc] initWithSource: jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.allowsInlineMediaPlayback = YES;
//    [config.userContentController addUserScript:wkUScript];
    self.webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:config];
    self.webView.navigationDelegate = self;


    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]]];
    
    [self.view addSubview:self.webView];

    [self.view addSubview:self.myProgressView];

    if(@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    for (UIView *_aView in [self.webView subviews])
     {
         if ([_aView isKindOfClass:[UIScrollView class]])
         {
             [(UIScrollView *)_aView setShowsVerticalScrollIndicator:NO];
             //右侧的滚动条
             [(UIScrollView *)_aView setShowsHorizontalScrollIndicator:NO];
             //下侧的滚动条
             for (UIView *_inScrollview in _aView.subviews)
             {
                 if ([_inScrollview isKindOfClass:[UIImageView class]])
                 {
                     _inScrollview.hidden = YES;  //上下滚动出边界时的黑色的图片
                 }
             }
         }
     };
    self.webView.scrollView.bounces = NO;
    
    self.spin = [[UIActivityIndicatorView alloc] init];
    self.spin.color = UIColor.lightGrayColor;
    self.spin.hidesWhenStopped = YES;
    
    self.spin.frame = (CGRect){0,0,40,40};
    self.spin.center = CGPointMake(kScreenW / 2.0f, kScreenH / 2.5);

    
    [self.view addSubview:self.spin];
    

}

- (void)loadUrl:(NSString *)url{
    
    self.webUrl = url;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]]];
    });
}
- (void)showBottomView{
    
}
- (void)hideBottomView{
    
}

- (UIProgressView *)myProgressView
{
    if (_myProgressView == nil) {
        _myProgressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0,0, kScreenW, 0)];
        _myProgressView.tintColor = [RPAppManager themColor];
        _myProgressView.trackTintColor = [UIColor clearColor];
    }
    
    return _myProgressView;
}

- (void)shareMethod{
    if (self.shareItem != nil) {
        [self commonShareWithCurrentModel:self.shareItem];
    }else{
        [self.webView evaluateJavaScript:@"ShareHtml()" completionHandler:nil];
    }
}

// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        self.myProgressView.alpha = 1.0f;
        [self.myProgressView setProgress:newprogress animated:YES];
        
        if (self.isUseSpin) {
            if (![self.spin isAnimating]) {
                [self.spin startAnimating];
            }
            if (newprogress >= 1.0f) {
                if ([self.spin isAnimating]) {
                    [self.spin stopAnimating];
                }
            }
        }else{
            if (newprogress >= 1.0f) {
                [UIView animateWithDuration:0.3f
                                      delay:0.3f
                                    options:UIViewAnimationOptionCurveEaseOut
                                 animations:^{
                                     self.myProgressView.alpha = 0.0f;
                                 }
                                 completion:^(BOOL finished) {
                                     [self.myProgressView setProgress:0 animated:NO];
                                 }];
            }
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"ShareObject"]) {
        //没有参数
        HomePageWebShareModel *shareModel = [HomePageWebShareModel mj_objectWithKeyValues:message.body];
        [self commonShareWithCurrentModel:shareModel];
    }
    if ([message.name isEqualToString:@"doUnLoginLikeMethod"] ||
        [message.name isEqualToString:@"doUnLoginSendCommentMethod"] ||
        [message.name isEqualToString:@"deleteUnLoginMethod"] ||
        [message.name isEqualToString:@"toLogin"] ||
        [message.name isEqualToString:@"Login"]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
    }
    if ([message.name isEqualToString:@"userInfoAddBlackList"]) {
        
    }
    
    if ([message.name isEqualToString:@"showUserInfo"]) {
        if ([RPAppManager isLogin]) {
            NSDictionary *resulst = message.body;
            NSInteger userId = [resulst[@"userId"] intValue];
            [MGJRouter openURL:@"local://ddup/homePage/userInfo" withUserInfo:@{@"navigationVC":self.navigationController,@"userId":@(userId),@"loadType":@(1)} completion:nil];
        }else{
            [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        }
    }
    if ([message.name isEqualToString:@"doReportMethod"]) {
        if ([RPAppManager isLogin]) {
            NSDictionary *resulst = message.body;
            NSString *commentId = resulst[@"commentId"];
            [MGJRouter openURL:@"local://ddup/report" withUserInfo:@{@"navigationVC":self.navigationController,@"reportId":@(commentId.intValue) ,@"reportType":@(0)} completion:nil];
        }else{
            [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        }
    }
    if ([message.name isEqualToString:@"noData"]) {
        NSDictionary *resulst = message.body;
        BOOL status = [resulst[@"status"] boolValue];
        if (status) {
            UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]init];
            self.navigationItem.rightBarButtonItem = rightItem;
            self.navigationItem.leftBarButtonItem.image = [UIImage imageNamed:@"common_back_white_tag"];
        }
    }
    if ([message.name isEqualToString:@"showShareItem"]) {
        NSDictionary *resulst = message.body;
        BOOL status = [resulst[@"status"] boolValue];
        if (status) {
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"common_share_tag"] style:UIBarButtonItemStyleDone target:self action:@selector(shareMethod)];
        }
    }
    
    if ([message.name isEqualToString:@"showNavTitle"]) {
        NSDictionary *resulst = message.body;
        NSString *title = resulst[@"title"];
        self.navigationItem.title = title;
    }
    
    if ([message.name isEqualToString:@"dynamic"]) {
        NSDictionary *resulst = message.body;
        NSInteger postId = [resulst[@"postId"] intValue];
        [self showDataLoadState];
        NSMutableDictionary *parma = [NSMutableDictionary dictionary];
        parma[@"userId"] = [RPAppManager getCustomerId];
        parma[@"postId"] = @(postId);
        parma[@"md5"] = [RPAppManager md5StrWithApi:GetNewPostDetail];
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetNewPostDetail) parames:parma success:^(id responseObj) {
            [self hideDataLoadLoadState];
            NSArray *resultArray = @[[HomePageItemModel mj_objectWithKeyValues:responseObj[RESPONSE]]];
            
            HomePageItemModel *itemModel = [resultArray firstObject];
            if ([itemModel.deleted boolValue]) {
                [WHToast showMessage:@"该动态已删除" duration:2 finishHandler:nil];
                return;
            }
            
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            param[kXHItemType] = @(XHPageDetailItemTypeNormal);
            param[kXHScrollUnEnable] = @(YES);
            param[kXHShowUserInfo] = @(YES);
            param[kXHListSource] = resultArray;
            param[kXHPlatformType] = @(XHPageDetailPlatformTypeHtml);
            HomePageDetailViewController *dtlVC = [[HomePageDetailViewController alloc]initWithConfigInfo:param];
            [self.navigationController pushViewController:dtlVC animated:YES];
            
        } failure:^(NSError *error) {
            [self hideDataLoadLoadState];
            [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        }];
    }
    if ([message.name isEqualToString:@"savePic"]) {
        
    }
    
    
    
    // ---------------------------- 新增方法名
    
    if ([message.name isEqualToString:@"getPageInfo"]) {
        NSDictionary *result = [message.body mj_JSONObject];
        WebSystemModel *deviceModel = [[WebSystemModel alloc]init];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"callbackId"] = result[@"callbackId"];
        param[@"code"] = @0;
        param[@"data"] = [deviceModel mj_JSONString];
        NSString *json = [param mj_JSONString];
        [self.webView evaluateJavaScript:[NSString stringWithFormat:@"doCallback(%@)",json] completionHandler:nil];
    }
    if ([message.name isEqualToString:@"getAppInfo"]) {
        NSDictionary *result = [message.body mj_JSONObject];
        
        WebDeviceModel *deviceModel = [[WebDeviceModel alloc]init];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"callbackId"] = result[@"callbackId"];
        param[@"code"] = @0;
        param[@"data"] = [deviceModel mj_JSONString];
        NSString *json = [param mj_JSONString];
        [self.webView evaluateJavaScript:[NSString stringWithFormat:@"doCallback(%@)",json] completionHandler:nil];
    }
    if ([message.name isEqualToString:@"setPageConfig"]) {
        NSDictionary *result = [message.body mj_JSONObject];
        self.navigationItem.title = result[@"navTitle"];
        // 显示关闭按钮
        if ([result[@"isCloseShow"] boolValue]) {
            UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]init];
            self.navigationItem.rightBarButtonItem = rightItem;
            self.navigationItem.leftBarButtonItem.image = [UIImage imageNamed:@"common_back_white_tag"];
        }
        // 显示正常返回按钮
        if (result[@"isBackShow"]) {
            self.navigationItem.leftBarButtonItem.image = [UIImage imageNamed:@"common_back_tag"];
        }
        // 显示分享按钮
        if (result[@"navShareInfo"] != nil) {
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"common_share_tag"] style:UIBarButtonItemStyleDone target:self action:@selector(shareMethod)];
            self.shareItem = [HomePageWebShareModel mj_objectWithKeyValues:result[@"navShareInfo"]];
        }else{
            UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]init];
            self.navigationItem.rightBarButtonItem = rightItem;
            self.shareItem = nil;
        }
        
        if ([result[@"bottomBarVisible"] boolValue]) {
            // 显示
            [self showBottomView];
        }else{
            // 隐藏
            [self hideBottomView];
            
        }
        
    }
    if ([message.name isEqualToString:@"showShareMenu"]) {
        HomePageWebShareModel *shareModel = [HomePageWebShareModel mj_objectWithKeyValues:message.body];
        [self commonShareWithCurrentModel:shareModel];
    }
    if ([message.name isEqualToString:@"openUrl"]) {
        NSDictionary *result = [message.body mj_JSONObject];
        NSString *url = result[@"url"];
        [[XHPushVCTool sharedXHPushVCTool] pushTargetVCWithUrl:url paramUrl:nil];
    }
    if ([message.name isEqualToString:@"getUserInfo"]) {
        NSDictionary *result = [message.body mj_JSONObject];
        WebUserInfoModel *userInfo = [[WebUserInfoModel alloc]init];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"callbackId"] = result[@"callbackId"];
        param[@"code"] = @0;
        
        if (userInfo.id.length == 0) {
            param[@"data"] = [NSNull null];
        }else{
            param[@"data"] = [userInfo mj_JSONString];
        }
        NSString *json = [param mj_JSONString];
        [self.webView evaluateJavaScript:[NSString stringWithFormat:@"doCallback(%@)",json] completionHandler:^(id _Nullable res, NSError * _Nullable error) {
            NSLog(@"111");
        }];
    }
    if ([message.name isEqualToString:@"goBack"]) {
        if ([self.webView canGoBack]) {
            [self.webView goBack];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    if ([message.name isEqualToString:@"close"]) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    if ([message.name isEqualToString:@"shareToPlatform"]) {
        NSDictionary *result = [message.body mj_JSONObject];
        WebShareModel *model = [WebShareModel mj_objectWithKeyValues:result];
        // 动态
        if (model.type.intValue == 1) {
            
        // 咨询
        }else if (model.type.intValue == 2){
            [self shareNewsWithCurrentModel:model];
        }
    }
    if ([message.name isEqualToString:@"sendEvent"]) {
        NSDictionary *result = [message.body mj_JSONObject];
        WebActionModel *model = [WebActionModel mj_objectWithKeyValues:result];
        if ([model.type isEqualToString:@"CollectionEvent"]) {
            BOOL isAdd = [model.event.action isEqualToString:@"add"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshNewsCollectionList" object:nil userInfo:@{@"newsId":model.event.id,@"status":@(isAdd)}];
        }
    }
    if ([message.name isEqualToString:@"handleResponse"]) {
        NSDictionary *result = [message.body mj_JSONObject];
        NSNumber *code = result[@"code"];
        if (code.intValue == 10010 || code.intValue == 10009) {
            
            if ([[RPAppManager jsd_findVisibleViewController] isKindOfClass:[self class]]) {
                [UserInfoModel deleteUserInfo];
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                loginVC.isAppLogin = YES;
                NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:loginVC];
                [UIApplication sharedApplication].keyWindow.rootViewController = nav;
                NSString *msg = code.intValue == 10010?@"帐号异常，请联系客服":@"登录状态已失效，请重新登录";
                [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:msg duration:2 finishHandler:nil];
                
            }
        }
    }
}

- (void)addAllScriptMsgHandle{
    WKUserContentController *userCC = self.webView.configuration.userContentController;
    //添加消息处理的handler的name
    [userCC addScriptMessageHandler:self name:@"dynamic"];
    [userCC addScriptMessageHandler:self name:@"ShareObject"];
    [userCC addScriptMessageHandler:self name:@"doUnLoginLikeMethod"];
    [userCC addScriptMessageHandler:self name:@"showUserInfo"];
    [userCC addScriptMessageHandler:self name:@"doUnLoginSendCommentMethod"];
    [userCC addScriptMessageHandler:self name:@"doReportMethod"];
    [userCC addScriptMessageHandler:self name:@"deleteUnLoginMethod"];
    [userCC addScriptMessageHandler:self name:@"userInfoAddBlackList"];
    [userCC addScriptMessageHandler:self name:@"noData"];
    [userCC addScriptMessageHandler:self name:@"showShareItem"];
    [userCC addScriptMessageHandler:self name:@"toLogin"];
    [userCC addScriptMessageHandler:self name:@"savePic"];
    [userCC addScriptMessageHandler:self name:@"showNavTitle"];
    
    
    /*
        ----------------新的方法-------------------
     */
    [userCC addScriptMessageHandler:self name:@"getAppInfo"];
    [userCC addScriptMessageHandler:self name:@"getPageInfo"];
    [userCC addScriptMessageHandler:self name:@"setPageConfig"];
    [userCC addScriptMessageHandler:self name:@"showShareMenu"];
    [userCC addScriptMessageHandler:self name:@"openUrl"];
    [userCC addScriptMessageHandler:self name:@"getUserInfo"];
    [userCC addScriptMessageHandler:self name:@"goBack"];
    [userCC addScriptMessageHandler:self name:@"close"];
    [userCC addScriptMessageHandler:self name:@"shareToPlatform"];
    [userCC addScriptMessageHandler:self name:@"sendEvent"];
    [userCC addScriptMessageHandler:self name:@"handleResponse"];
    
}

- (void)removeAllScriptMsgHandle{
    WKUserContentController *controller = self.webView.configuration.userContentController;
    [controller removeScriptMessageHandlerForName:@"ShareObject"];
    [controller removeScriptMessageHandlerForName:@"dynamic"];
    [controller removeScriptMessageHandlerForName:@"doUnLoginLikeMethod"];
    [controller removeScriptMessageHandlerForName:@"showUserInfo"];
    [controller removeScriptMessageHandlerForName:@"doUnLoginSendCommentMethod"];
    [controller removeScriptMessageHandlerForName:@"doReportMethod"];
    [controller removeScriptMessageHandlerForName:@"deleteUnLoginMethod"];
    [controller removeScriptMessageHandlerForName:@"userInfoAddBlackList"];
    [controller removeScriptMessageHandlerForName:@"noData"];
    [controller removeScriptMessageHandlerForName:@"showShareItem"];
    [controller removeScriptMessageHandlerForName:@"toLogin"];
    [controller removeScriptMessageHandlerForName:@"savePic"];
    [controller removeScriptMessageHandlerForName:@"showNavTitle"];
    
    /*
        ----------------新的方法-------------------
     */
    [controller removeScriptMessageHandlerForName:@"getAppInfo"];
    [controller removeScriptMessageHandlerForName:@"getPageInfo"];
    [controller removeScriptMessageHandlerForName:@"setPageConfig"];
    [controller removeScriptMessageHandlerForName:@"showShareMenu"];
    [controller removeScriptMessageHandlerForName:@"openUrl"];
    [controller removeScriptMessageHandlerForName:@"getUserInfo"];
    [controller removeScriptMessageHandlerForName:@"goBack"];
    [controller removeScriptMessageHandlerForName:@"close"];
    [controller removeScriptMessageHandlerForName:@"shareToPlatform"];
    [controller removeScriptMessageHandlerForName:@"sendEvent"];
    [controller removeScriptMessageHandlerForName:@"handleResponse"];
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
  
    self.isLoadFinish = YES;
    
    __weak typeof(self)weakSelf = self;
    [self.webView evaluateJavaScript:@"ShowTitle()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        weakSelf.navigationItem.title = result;
    }];
}



#pragma mark - 分享咨询
- (void)shareNewsWithCurrentModel:(WebShareModel *)itemModel{
    UMSocialPlatformType type = UMSocialPlatformType_UnKnown;
    switch (itemModel.platform.intValue) {
        case 1:
            type = UMSocialPlatformType_WechatSession;
            break;
        case 2:
            type = UMSocialPlatformType_WechatTimeLine;
            break;
        case 3:
            type = UMSocialPlatformType_QQ;
            break;
        case 4:
            type = UMSocialPlatformType_Qzone;
        break;
        case 5:
            type = UMSocialPlatformType_Sina;
            break;
        default:
            break;
    }
    if (![[UMSocialManager defaultManager] isInstall:type]) {
        if (type == UMSocialPlatformType_WechatSession || type == UMSocialPlatformType_WechatTimeLine) {
            [WHToast showMessage:@"请先安装微信" duration:2 finishHandler:nil];
        }
        if (type == UMSocialPlatformType_QQ || type == UMSocialPlatformType_Qzone) {
            [WHToast showMessage:@"请先安装QQ" duration:2 finishHandler:nil];
        }
        if (type == UMSocialPlatformType_Sina) {
            [WHToast showMessage:@"请先安装微博" duration:2 finishHandler:nil];
        }
        return;
    }
    
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    NSString *title = itemModel.title;
    NSString* thumbURL =  itemModel.image;
    NSString *desc = itemModel.desc;
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:desc thumImage:thumbURL];
    //设置网页地址
    shareObject.webpageUrl = itemModel.url;
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:type messageObject:messageObject currentViewController:nil completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
          
        }
    }];
}


#pragma mark - 分享统一方法
- (void)commonShareWithCurrentModel:(HomePageWebShareModel *)itemModel{
        
    if (!self.isLoadFinish) {
        return;
    }
    
    [RPAppShareView showCompleteblock:^(XHShareViewPlatformType platformType) {
        UMSocialPlatformType type = UMSocialPlatformType_UnKnown;
        switch (platformType) {
            case XHShareViewPlatformTypeWeChatSession:
                type = UMSocialPlatformType_WechatSession;
                break;
            case XHShareViewPlatformTypeWeChatMoments:
                type = UMSocialPlatformType_WechatTimeLine;
                break;
            case XHShareViewPlatformTypeQQ:
                type = UMSocialPlatformType_QQ;
                break;
                
            case XHShareViewPlatformTypeQQZone:
                type = UMSocialPlatformType_Qzone;
                break;
            
            case XHShareViewPlatformTypeQQWeibo:
                type = UMSocialPlatformType_Sina;
                break;
            default:
                break;
        }
        
        if (![[UMSocialManager defaultManager] isInstall:type]) {
            if (type == UMSocialPlatformType_WechatSession || type == UMSocialPlatformType_WechatTimeLine) {
                [WHToast showMessage:@"请先安装微信" duration:2 finishHandler:nil];
            }
            if (type == UMSocialPlatformType_QQ || type == UMSocialPlatformType_Qzone) {
                [WHToast showMessage:@"请先安装QQ" duration:2 finishHandler:nil];
            }
            if (type == UMSocialPlatformType_Sina) {
                [WHToast showMessage:@"请先安装微博" duration:2 finishHandler:nil];
            }
            return;
        }
    
        
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];

        NSString *title = itemModel.title.length == 0?@"DDup":itemModel.title;
        
        
        NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];

        NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];

        UIImage *shareImage= [UIImage imageNamed:icon];
        
        NSString* thumbURL =  itemModel.image;
        
        NSString *desc = itemModel.desc;
        if (itemModel.type.intValue == 1) {
            desc = itemModel.desc.length!=0?itemModel.desc:@"分享我的Chinese高考";
        }
        //创建网页内容对象
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:desc thumImage:thumbURL.length==0?shareImage:thumbURL];
        //设置网页地址
        shareObject.webpageUrl = itemModel.url;
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:type messageObject:messageObject currentViewController:nil completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
              
            }
        }];
    }];
}

/*
 -(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures

 {

     if (!navigationAction.targetFrame.isMainFrame) {

         [webView loadRequest:navigationAction.request];

     }

     return nil;

 } 
 */

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}


#pragma mark - dealloc
- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

@end
